<template>
  <div class="address-edit">
    <s-Header :name="state.type === 'add' ? '新增地址' : '编辑地址'" >
      <!-- 通过默认插槽 穿透插入sHeader中popover组件default插槽中 -->
      <template #popover_default="{action}">
        <van-grid
            square
            clickable
            :border="false"
            column-num="3"
            style="width: 240px;"
          >
            <van-grid-item
              v-for="(item,index) in action"
              :key="index"
              :text="item.text"
              :icon="item.icon || photo-o"
            />
          </van-grid>
      </template>
    </s-Header>
    <!-- 地址编辑器 -->
    <div class="edit-form" >
      <van-address-edit
        :area-list="areaList"
        show-delete
        show-set-default
        show-search-result
        :address-info="state.addressInfo"
        :search-result="searchResult"
        :area-columns-placeholder="['请选择省份', '请选择城市', '请选择区县']"
        @save="onSave"
        @delete="onDelete"
        @change-detail="onChangeDetail"
      />
      </div>
  </div>
</template>
<script setup>
  import { reactive, ref, isRef, isReactive,nextTick, onUnmounted, onMounted  } from 'vue'
  import { showSuccessToast, showFailToast, showLoadingToast, closeToast, showToast } from 'vant'
  import { useRoute, useRouter } from 'vue-router'
    // 直接使用Vant 提供了一份中国省市区数据
  /* 
    地址数据格式
    const areaList = {
      province_list: {
        110000: '北京市',
        120000: '天津市',
      },
      city_list: {
        110100: '北京市',
        120100: '天津市',
      },
      county_list: {
        110101: '东城区',
        110102: '西城区',
        // ....
      },
    }
  */
  import { areaList } from '@vant/area-data';
  import { setLocal, getLocal, tdist } from '@/common/js/utils'
  import { getAddressDetail, addAddress, EditAddress, DeleteAddress } from '@/service/address'
  import sHeader from '@/components/SimpleHeader.vue'

  const router = useRouter();
  const route = useRoute();
  console.log('route...',route,route.query)

  // const areaList = reactive({
  //   province_list: {},
  //   city_list: {},
  //   county_list: {}
  // })

  const state = reactive({
    type: 'add', // 增/改
    addressId: '', // 该条数据id
    addressInfo: {}, // 反显数据
    from: route.query.from // 从那个页面过来
  })
  console.log(1111,tdist.getLev1())
  onMounted(async()=>{
    /* // 省市区列表构造
    let _province_list = {}
    let _city_list = {}
    let _county_list = {}
    tdist.getLev1().forEach(p => {
      _province_list[p.id] = p.text
      tdist.getLev2(p.id).forEach(c => {
        _city_list[c.id] = c.text
        tdist.getLev3(c.id).forEach(q => _county_list[q.id] = q.text)
      })
    })
    areaList.province_list = _province_list
    areaList.city_list = _city_list
    areaList.county_list = _county_list */
    // 获取跳转携带相关参数
    const {type, addressId, from} = route.query;
    state.type = type;
    state.addressId = addressId;
    state.from = from || '';
    if(state.type === 'edit'){
      const { data: addressDetail } = await getAddressDetail( addressId)
      console.log(222222,addressDetail)
      

      // 保存时省市区向后台传递的实际是 对应名称
      // 邮编一般为区的编号
      // 有些些区会重名
      let _areaCode = '';
      const provinceEntries = Object.entries(areaList.province_list);
      const cityEntries = Object.entries(areaList.city_list);
      const countyEntries = Object.entries(areaList.county_list);

      // const getCountyCode
      const provinceCode = provinceEntries.find(item=> item[1] === addressDetail.provinceName)?.[0];
      const cityCode = cityEntries.find(item=> item[1] === addressDetail.cityName)?.[0];
      const countyCode = countyEntries.find(item=> item[1] === addressDetail.regionName)?.[0];
      console.log('getCode...',countyCode, cityCode, provinceCode)
      if(countyCode.slice(2,4) === cityCode.slice(2,4) && countyCode.slice(0,2) === provinceCode.slice(0,2)){
        _areaCode = countyCode;
      }
      console.log(22222,_areaCode)
      // state内部为深层proxy,改变指向会丢失之前的动态绑定
      // state.addressInfo = addressDetail;
      const getData = {
        id: addressDetail.addressId,
        name: addressDetail.userName,
        tel: addressDetail.userPhone,
        province: addressDetail.provinceName,
        city: addressDetail.cityName,
        county: addressDetail.regionName,
        addressDetail: addressDetail.detailAddress,
        // areaCode: _areaCode,
        isDefault: !!addressDetail.defaultFlag
      }
       state.addressInfo = Object.assign( state.addressInfo,getData)
    }
    
  })

  const searchResult = ref([]);
  const onChangeDetail = (val) => {
    if (val) {
      // 配合后台查询接口返回数据
      // 搜索展示相关数据
      searchResult.value = [
        {
          name: '黄龙万科中心',
          address: '杭州市西湖区',
        },
      ];
    } else {
      searchResult.value = [];
    }
  };

  const onSave = async (content) => {
    console.log('onSave...',content)
    const params = {
      userName: content.name,
      userPhone: content.tel,
      provinceName: content.province,
      cityName: content.city,
      regionName: content.county,
      detailAddress: content.addressDetail,
      defaultFlag: content.isDefault ? 1 : 0,
    }
    if (state.type == 'edit') {
      params['addressId'] = state.addressId
    }
    await state.type == 'add' ? addAddress(params) : EditAddress(params)
    showToast('保存成功')
    setTimeout(() => {
      router.back()
    }, 1000)
  }

  const onDelete = async () => {
    await DeleteAddress(state.addressId)
    showToast('删除成功')
    setTimeout(() => {
      router.back()
    }, 1000)
  }

</script>
  
<style lang="less" >
  .address-edit{
    .van-address-edit__fields{
      box-shadow: 1px 1px 4px 0px #ccc;
    }
    .van-address-edit__default{
      box-shadow: 1px 1px 4px 0px #ccc;
    }
  }
</style>
<style lang="less" scoped>
  .address-edit{
    .van-address-edit__fields{
      box-shadow: 1px 1px 4px 0px #ccc;
    }
    .van-address-edit__default{
      box-shadow: 1px 1px 4px 0px #ccc;
    }
  }
</style>